04. Initializing Vector Values

Initializing Vector Values

In the previous part of the lesson, you learned to declare a vector first and then assign values:

vector<float> myvector(5);

myvector[0] = 5.0;
myvector[1] = 3.0;
myvector[2] = 2.7;
myvector[3] = 8.2;
myvector[4] = 7.9;

There are various other ways for assigning initial values to a vector. Here are two other ways:

Declaring and Defining Simultaneously

When declaring a vector, you can also assign initial values simultaneously.

std::vector<int> myvector (10, 6);

The code will declare a vector with ten elements, and each element will have the value 6.

Declaring and Defining Simultaneously with Brackets

There is another way to initialize a vector as well if you are using one of the more recent versions of C++ such as C++11 or C++17; You could also do something like:

std::vector<float> myvector = {5.0, 3.0, 2.7, 8.2, 7.9}

The different versions of C++ (C++98, C++11, C++14, and C++17) will be discussed in the Practical C++ lesson.

Practice Declaring and Defining Vectors

In the space below, follow the TODOs. When you are finished, check out the solution.cpp file.

Start Quiz:

// TODO: Include the iostream and vector libraries

// TODO: Use the standard namespace

// TODO: Write a main function
int main() {}
// TODO: Inside the main function, do the following:
/***       
 * 1. declare a float vector with 4 elements 
 * 2. fill the float vector with the following values: 4.5, 2.1, 8.54, 9.0
 * 
 * 3. declare and define a float vector with one line of code. The float vector
 * should have four elements with the following values: 3.5, 3.5, 3.5, 3.5
 * 
 * NOTE: You cannot use the bracket syntax because
 * the classroom compiles your code with C++98. The bracket syntax was introduced 
 * in C++11.
 ***/
#include <vector>

using namespace std;

int main() {
    
    vector<float> vector1(4);
    vector1[0] = 4.5;
    vector1[1] = 2.1;
    vector1[2] = 8.54;
    vector1[3] = 9.0;

    vector<float> vector(4, 3.5);
    
    return 0;
}